package com.bjfu.gmms.servlet.mentorServlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.MentorMapper;
import com.bjfu.gmms.model.Mentor;
import com.bjfu.gmms.model.Mentor2;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/mentor_view/updateMentorInfoServlet")
public class UpdateMentorInfoServlet extends HttpServlet {
    private MentorMapper mentorMapper;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        SqlSession sqlSession = MyBatisUtil.getSqlSession("development");
        try{
            mentorMapper=sqlSession.getMapper(MentorMapper.class);
            Mentor mentor = (Mentor) request.getSession().getAttribute("mentor");
            mentor.setMentorName(request.getParameter("mentorName"));
            mentor.setMentorDetails(request.getParameter("mentorDetails"));
            mentor.setMentorPhone(request.getParameter("mentorPhone"));
            mentor.setMentorMail(request.getParameter("mentorMail"));
            // 数据库更新
            mentorMapper.updateMentorInfo(mentor);
            sqlSession.commit();
            // 更新session中的mentor对象
            request.getSession().setAttribute("mentor", mentor);
            response.sendRedirect("mentor_info.jsp");
        }catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback(); // 发生异常时回滚事务
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新导师信息失败！");
        } finally {
            sqlSession.close(); // 确保资源被释放
        }
    }
}
